package com.hfh.server.netty_server.coder;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.hfh.server.netty_server.MessageDTO;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.nio.charset.Charset;
import java.util.List;

/**
 * @author liuxinghong
 * @Description:  收到消息后二进制字节码转换成message   解码器
 * @date 2019/9/3 000319:16
 */
public class NettyMessageDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {

        byte[] data = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(data);
        String str = new String(data, Charset.forName("UTF-8"));
        MessageDTO messageDTO = JSON.parseObject(str, new TypeReference<MessageDTO>() {
        });
        out.add(messageDTO);
    }


}
